import {createAsyncThunk, createSlice, PayloadAction} from '@reduxjs/toolkit';

import { StatePagingType } from 'storage/redux';
import RequestStatus from 'storage/redux/RequestStatus';
import {Report, ReportUpdate} from "type/entity/Report";
import {PagingData, PagingResult} from "type/Page";
import RequestHandler from "http/RequestHandler";
import {builderPagingHandler} from "./index";

/** 请求报销单表分页数据 */
export const fetchReportPageData = createAsyncThunk(
    'report/fetchReportPageData',
    async (paging: PagingData) => {
        return await RequestHandler.get<PagingResult<Report>>("/record/report/page/" + paging.page + "/" + paging.pageSize);
    }
);

/** 添加报销单表数据 */
export const fetchAddReport = createAsyncThunk(
    'report/fetchAddReport',
    async (vo: Report) => {
        return await RequestHandler.put<number>("/record/report", vo);
    }
);

/** 更新报销单表数据 */
export const fetchUpdateReport = createAsyncThunk(
    'report/fetchUpdateReport',
    async (vo: Report) => {
        return await RequestHandler.post<number>("/record/report", vo);
    }
);

/** 更新报销单表数据 */
export const fetchUpdateReportTotalAmount = createAsyncThunk(
    'report/fetchUpdateReportTotalAmount',
    async (update: ReportUpdate) => {
        return await RequestHandler.post<number>("/record/report/update", update);
    }
);

/**
 * 报销单表状态管理类型
 */
export type ReportState = StatePagingType<Report>

/** 状态初始化数据 */
const initialState: ReportState = {
    data: [],
    loading: false,
    requestStatus: RequestStatus.INIT,
    currentPage: 1,
    pageSize: 10,
    // pageSize: UserStorage.getInstance().getAdminPageConfigFromLocalStore().reportPageSize,
    total: 0,
    totalPage: 10
};

export const reportSlice = createSlice({
    name: 'report',
    initialState,
    reducers: {
        /**
         * 向redux中添加报销单表信息
         */
        addReport: (state, action: PayloadAction<Report>) => {
            state.data.push(action.payload);
        }
    },
    extraReducers: (builder) => {
        builderPagingHandler(builder, fetchReportPageData);
        /** 添加报销单表信息 */
        builder.addCase(fetchAddReport.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
        });
        /** 修改报销单表信息 */
        builder.addCase(fetchUpdateReport.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
        });

        builder.addCase(fetchUpdateReportTotalAmount.fulfilled, (state, action) => {
            state.requestStatus = RequestStatus.REFRESH;
        });
        // /** 报销单表用户信息 */
        // builder.addCase(fetchDeleteReport.fulfilled, (state, action) => {
        //     state.requestStatus = RequestStatus.REFRESH;
        // });
    }
});

export const {addReport} = reportSlice.actions;
export default reportSlice.reducer;

